package com.mobilesales.android.activities.products;

import java.util.List;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.mobilesales.android.R;
import com.mobilesales.android.activities.ModelActivity;
import com.mobilesales.android.database.ProductManager;
import com.mobilesales.android.infrastructure.DownloadImagesTask;
import com.mobilesales.android.model.dictionary.Dictionary;
import com.mobilesales.android.model.params.FieldType;
import com.mobilesales.android.model.params.Param;
import com.mobilesales.android.model.products.Product;
import com.mobilesales.android.model.products.ProductImage;
import com.mobilesales.android.util.Constants;
import com.mobilesales.android.util.MessageBox;

public class DetailsProduct extends ModelActivity<Product> {

	private int productId;

	private TextView nameField;
	private TextView skuField;
	private TextView quantityField;
	private TextView minQuantityField;
	private TextView orderQuantityField;
	private TextView spreadField;
	private TextView symbolField;
	private TextView isMarketingItemOnlyField;
	private TextView taxField;
	private TextView unitField;
	private TextView priceField;

	private LinearLayout photosLayout;
	private Gallery gallery;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.product_details);

		nameField = (TextView) this.findViewById(R.id.nameTxt);
		skuField = (TextView) this.findViewById(R.id.skuTxt);
		quantityField = (TextView) this.findViewById(R.id.quantityTxt);
		minQuantityField = (TextView) this.findViewById(R.id.minQuantityTxt);
		orderQuantityField = (TextView) this
				.findViewById(R.id.orderQuantityTxt);
		spreadField = (TextView) this.findViewById(R.id.spreadTxt);
		symbolField = (TextView) this.findViewById(R.id.symbolTxt);
		isMarketingItemOnlyField = (TextView) this
				.findViewById(R.id.isMarketingOnlyItemTxt);
		taxField = (TextView) this.findViewById(R.id.taxTxt);
		unitField = (TextView) this.findViewById(R.id.unitTxt);
		priceField = (TextView) this.findViewById(R.id.priceTxt);

		photosLayout = (LinearLayout) this.findViewById(R.id.photosLayout);
		gallery = (Gallery) this.findViewById(R.id.gallery);

		Bundle bundle = this.getIntent().getExtras();
		if (bundle != null && bundle.containsKey(Constants.ProductId)) {
			productId = bundle.getInt(Constants.ProductId);
			loadItem(productId);
		} else {
			MessageBox.show(this, getString(R.string.ErrorProduct));
		}
	}

	private void loadItem(int productId) {
		Product product = getProduct(productId);
		if (product != null) {
			this.setModel(product);
		} else {
			MessageBox.show(this, getString(R.string.ErrorProduct));
			finish();
		}
	}

	@Override
	protected void setModel(Product model) {
		super.setModel(model);
		nameField.setText(model.Name);
		skuField.setText(model.Sku);
		quantityField.setText(String.valueOf(model.Quantity));
		minQuantityField.setText(String.valueOf(model.MinQuantity));
		orderQuantityField.setText(String.valueOf(model.OrderQuantity));
		spreadField.setText(String.valueOf((int)(model.Spread*100))+" %");
		symbolField.setText(model.Symbol);
		isMarketingItemOnlyField
				.setText(model.IsMarketingOnlyItem ? getString(R.string.Yes)
						: getString(R.string.No));
		taxField.setText(String.valueOf((int)(model.Tax.Value*100))+" %");
		unitField.setText(model.Unit.Name);
		priceField.setText(String.format("%1$,.2f", model.Price));

		if (model.Images != null && model.Images.size() > 0) {
			
			/* localhost fix */
			for(ProductImage img : model.Images) {
				img.Path = img.Path.replace("localhost","10.0.2.2");
			}
			
			DownloadImagesTask dlImagesTsk = new DownloadImagesTask(this,
					model.Images, gallery);
			dlImagesTsk.execute();
		} else {
			photosLayout.setVisibility(View.GONE);
		}
		this.drawParams(model.Params);
	}

	private Product getProduct(int productId) {
		ProductManager manager = new ProductManager(this);
		Product result = manager.GetProduct(productId);
		manager.Close();
		return result;
	}

	public void refresh() {
		this.getHandler().post(new Runnable() {
			public void run() {
				loadItem(productId);
			}
		});
	}

	private void drawParams(Dictionary<Param, String> params) {
		TableLayout table = (TableLayout) this.findViewById(R.id.fields);
		if (params != null) {
			List<Param> keys = params.getKeys();
			for (Param param : keys) {

				TableRow tr = new TableRow(this);
				LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			    llp.setMargins(5, 5, 5, 5); // llp.setMargins(left, top, right, bottom);
			    tr.setLayoutParams(llp);
				TextView label = new TextView(this);
				llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			    llp.setMargins(0, 0, 15, 0); // llp.setMargins(left, top, right, bottom);
			    label.setLayoutParams(llp);
				
				label.setText(param.DisplayName);
				TextView txt = new TextView(this);

				String val = params.getValue(param);

				if (val == null || val == "") {
					val = param.DefaultValue != null ? param.DefaultValue : "";
				}
				if (param.FieldType == FieldType.Boolean) {
					boolean b = Boolean.parseBoolean(val.toLowerCase());
					txt.setText(b ? getString(R.string.Yes)
							: getString(R.string.No));
				} else if (param.FieldType == FieldType.Dictionary
						&& params.getValue(param) == null) {
					String[] splitted = val.split(";");
					txt.setText(splitted[0]);
				} else {
					txt.setText(val);
				}
				tr.addView(label);
				tr.addView(txt);
				table.addView(tr);
			}
		}
		table.invalidate();
	}
}
